import axios from 'axios';
import md5 from "md5";
var CryptoJS = require("crypto-js");

/**
* 截取URL参数
* @param {string} name 截取的key
* @param {string} [url] 被截取的url
* @returns {string} 截取的val
*/ 
export function urlParam(name, url) {
    let reg = new RegExp(".*[&?]" + name + "=([^&]*)(&|$)");
    let r;
    if (!url) {
        r = window.location.search.match(reg);
    } else {
        r = url.match(reg);
    }
    if (r) return decodeURIComponent(r[1]);
    return '';
}

//判断是否固定电话
export function isTel(phone) {
    var myreg = /^(0(10|21|22|23|[1-9][0-9]{2}))|400(-|)?[0-9]{7,8}$/;
    if (!myreg.test(phone)) {
        return false
    } else {
        return true
    }
}



/**
* 判断是否是手机号
* @param {string} val 传进来的字符串
*/
export function isMobile(val) {
    let myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(19[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if(!myreg.test(val)) {
        return false
    } else {
        return true
    }
}

/**
 * 密码判断
 * */
export function isPassword(val) {
    let reg = /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{8,18}$/;
    if(!reg.test(val)) {
        return false
    } else {
        return true
    }
}

/**
 * 密码判断
 * */
export function isPassword8(val) {
    let reg = /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{8,30}$/;
    if(!reg.test(val)) {
        return false
    } else {
        return true
    }
}

/**
 * 短信验证码判断
 * */
export function isCode(val) {
    let reg = /^\d{4}$/;
    if(!reg.test(val)) {
        return false
    } else {
        return true
    }
}

/**
 * 短信验证码判断 6位
 * */
export function isCode6(val) {
    let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6}$/;
    if (!reg.test(val)) {
        return false
    } else {
        return true
    }
}
export function Append_zore(temp) {
    if (temp < 10) {
        return "0" + temp;
    } else {
        return temp;
    }
}
/**
 * 身份证号码判断
 * */
export function isIdcard(val) {
    //获取证件号码  
    var person_id = val;
    //合法性验证  
    var sum = 0; 
    //出生日期  
    var birthday;
    //验证长度与格式规范性的正则  
    var pattern = new RegExp(
        /(^\d{15}$)|(^\d{17}(\d|x|X)$)/i);
    if(pattern.exec(person_id)) {
        //验证身份证的合法性的正则  
        pattern = new RegExp(
            /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/);
        if(pattern.exec(person_id)) {
            //获取15位证件号中的出生日期并转位正常日期       
            birthday = "19" + person_id.substring(6, 8) +
                "-" + person_id.substring(8, 10) +
                "-" + person_id.substring(10, 12);
        } else {
            person_id = person_id.replace(/x|X$/i, "a");
            //获取18位证件号中的出生日期  
            birthday = person_id.substring(6, 10) + "-" +
                person_id.substring(10, 12) + "-" +
                person_id.substring(12, 14);
            //校验18位身份证号码的合法性  
            for(var i = 17; i >= 0; i--) {
                sum += (Math.pow(2, i) % 11) * parseInt(person_id.charAt(17 - i), 11);
            }
            if(sum % 11 !== 1) {
                return false;
            }
        }
        var dateStr = new Date(birthday.replace(/-/g, "/"));
        if(birthday !== (dateStr.getFullYear() + "-" + Append_zore(dateStr.getMonth() + 1) + "-" + Append_zore(dateStr.getDate()))) {
            return false;
        }
    } else {
        return false;
    }
    return true;
}

//车牌号验证方法

export function isCarNum(vehicleNumber) {
    var xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
    var creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
    if (vehicleNumber.length == 7) {
        return creg.test(vehicleNumber);
    } else if (vehicleNumber.length == 8) {
        return xreg.test(vehicleNumber);
    } else {
        return false;
    }
}

/**
 * 价格判断
 */
export function isPrice(price) {
    var myreg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
    if (!myreg.test(price)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 价格判断--小数点后一位
 */
export function isPrice_1(price) {
    var myreg = /(^[1-9]\d*(\.\d{1})?$)|(^0(\.\d{1})?$)/;
    if (!myreg.test(price)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 去除空格
 *  */

export function Trim(str)
{
    var result;
    console.log(str)
    result = str.replace(/(^\s+)|(\s+$)/g, "");
    return result;
}
/**
 * 判断是否正整数
 *  */
export function isNum(reg) {
    var myreg = /^[1-9]+[0-9]*]*$/;
    if (!myreg.test(reg)) {
        return false
    } else {
        return true
    }
}
/**
 * 判断是否整数
 *  */
export function isInt(reg) {
    var myreg = /^\d+$/;
    if (!myreg.test(reg)) {
        return false
    } else {
        return true
    }
}


/**
 * 生成签名
 * @param array post参数
 * @param string APP Secret
 */
export function calc_sign(data) {
    const app_secret = process.env.NODE_ENV == 'production' ? '7c1a05ef3e481f0c8ea8dbb4e3a48af0' : '08d97eb42933eafda76524d8eb49ad5e';
    // const app_secret = process.env.NODE_ENV == 'production' ? '3e4f571182e72922a0210c08bbc0c0de' : '10b776e558f20ff619ca987a0035732e';   // 对接外平台 app_secret
    // delete data['sign'];
    delete data['file']; // 去除单文件上传file参数
    delete data['file[]']; // 去除多文件上传file参数
    var keys = [];
    for (var k in data) {
        keys.push(k);
    }
    keys.sort();
    var kv = [];
    for (var v of keys) {
        if (data[v] !== undefined){
            kv.push(v + '=' + data[v]);
        }
    }
    var kv_str = kv.join('&');
    return md5(app_secret + kv_str);
}

/**
 * 加密
 */
 export function EncryptEcb(word, keyStr) {
    keyStr = keyStr ? keyStr : 'cdd6ddf2019bdefc177132f5f8e90459';
    var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
    var srcs = CryptoJS.enc.Utf8.parse(word);
    console.log(word,keyStr)
    console.log(srcs,key)
    var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.toString();
}
/**
 * 解密
 * @param str
 */
export function DecryptEcb(word, keyStr) {
    keyStr = keyStr ? keyStr : 'cdd6ddf2019bdefc177132f5f8e90459';
    var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
    var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

//获取日期的月份天数。必须传入日期格式
export function getMonthDay(e) {
    const curDate = e ? new Date(e) : new Date();
    const curMonth = curDate.getMonth() + 1;
    curDate.setMonth(curMonth, 0)
    let days = curDate.getDate();
    console.log(days)
    return days;
}

//根据日期及加减天数计算日期，默认当前日期所在的周一日期。
export function getMonday(e, day){
    const time = e ? new Date(e) : new Date();
    const week = time.getDay(); //获取所传日期所在天数
    const minus = week ? week - 1 : 6; //距离周一有多少天
    const getMinus = day ? minus - day : minus; 
    time.setDate(time.getDate() - getMinus);
    const y = time.getFullYear();
    const m = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1;
    const d = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
    return y + '-' + m + '-' + d;
}

//获取日期day天之后的日期
export function getDayDate(e, day) {
    const time = e ? new Date(e) : new Date();
    time.setDate(time.getDate() + day);
    const y = time.getFullYear();
    const m = time.getMonth() + 1; //获取月份
    const d = time.getDate();
    return y + '-' + m + '-' + d;
}

//根据日期获取星期几
export function getWeek(dateString) {
    const dateArray = dateString.split("-");
    const date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
    return "周" + "日一二三四五六".charAt(date.getDay());
};

/**
 * 上传图片参数
 *  */ 
 export function setfileUploadDate(sys_id, source_id, type_id) {
    return EncryptEcb(JSON.stringify({
        'sign_key':'9d49b43f795704250e8a514f7d36411c',
        'sys_id':sys_id,
        'source_id': source_id,
        'type_id': type_id
    }), '35cdfe33a716f47e1c1878349f1286c1')
}
/**
 * 删除图片参数
 *  */
export function delfileUploadDate(att_id, att_url) {
    return {
        'fp': EncryptEcb(JSON.stringify({
            'sign_key': '2dff673c98f74c02105486c83be20eb3',
            'att_id': att_id,
            'att_url': att_url
        }),'35cdfe33a716f47e1c1878349f1286c1')
    }
}
/**
 * 阿拉伯数字处理成中文数字
 *  */
export function numToText(num,type) {

    const nums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
    const nums_1 = ['零', '一', '两', '三', '四', '五', '六', '七', '八', '九', '十']
    const arr = type ? nums_1 : nums;
    const numArr = String(num).split('');
    numArr.reverse();
    let newText = '';
    numArr.forEach((item, i) => {
        if (i === 0) {
            newText = arr[numArr[i]]
        } else if (i === 1) {
            newText = arr[numArr[i]] === '一' ? '十' : arr[numArr[i]] + '十' + (arr[numArr[i - 1]] === '零' ? '' : arr[numArr[i - 1]])
        } else if (i === 2) {
            newText = arr[numArr[i]] + '百' + (arr[numArr[i - 1]] === '零' ? arr[numArr[i - 1]] : arr[numArr[i - 1]] + '十') + (arr[numArr[i - 2]] === '零' ? '' : arr[numArr[i - 2]])
        } else if (i === 3) {
            newText = arr[numArr[i]] + '千' + arr[numArr[i - 1]] + '百' + arr[numArr[i - 2]] + '十' + (arr[numArr[i - 3]] === '零' ? '' : arr[numArr[i - 3]])
        }
    })
    return newText
}
export const carDataProvince = [
    {name:'京',value:'京'},
    {name:'津',value:'津'},
    {name:'沪',value:'沪'},
    {name:'渝',value:'渝'},
    {name:'冀',value:'冀'},
    {name:'豫',value:'豫'},
    {name:'云',value:'云'},
    {name:'辽',value:'辽'},
    {name:'黑',value:'黑'},
    {name:'湘',value:'湘'},
    {name:'皖',value:'皖'},
    {name:'鲁',value:'鲁'},
    {name:'新',value:'新'},
    {name:'苏',value:'苏'},
    {name:'浙',value:'浙'},
    {name:'赣',value:'赣'},
    {name:'鄂',value:'鄂'},
    {name:'桂',value:'桂'},
    {name:'甘',value:'甘'},
    {name:'晋',value:'晋'},
    {name:'蒙',value:'蒙'},
    {name:'陕',value:'陕'},
    {name:'吉',value:'吉'},
    {name:'闽',value:'闽'},
    {name:'贵',value:'贵'},
    {name:'粤',value:'粤'},
    {name:'青',value:'青'},
    {name:'藏',value:'藏'},
    {name:'川',value:'川'},
    {name:'宁',value:'宁'},
    {name:'琼',value:'琼'},
    {name:'使',value:'使'},
    {name:'领',value:'领'},
]
export const carDataA_Z=[
    {name:'A',value:'A'},
    {name:'B',value:'B'},
    {name:'C',value:'C'},
    {name:'D',value:'D'},
    {name:'E',value:'E'},
    {name:'F',value:'F'},
    {name:'G',value:'G'},
    {name:'H',value:'H'},
    {name:'I',value:'I'},
    {name:'J',value:'J'},
    {name:'K',value:'K'},
    {name:'L',value:'L'},
    {name:'M',value:'M'},
    {name:'N',value:'N'},
    {name:'O',value:'O'},
    {name:'P',value:'P'},
    {name:'Q',value:'Q'},
    {name:'R',value:'R'},
    {name:'S',value:'S'},
    {name:'T',value:'T'},
    {name:'U',value:'U'},
    {name:'V',value:'V'},
    {name:'W',value:'W'},
    {name:'X',value:'X'},
    {name:'Y',value:'Y'},
    {name:'Z',value:'Z'},
]

export default {
    urlParam,
    isTel,
    isMobile,
    isPassword,
    isPassword8,
    isCode,
    isCode6,
    isIdcard,
    isCarNum,
    isPrice,
    isPrice_1,
    Trim,
    isNum,
    isInt,
    calc_sign,
    getMonthDay,
    getMonday,
    setfileUploadDate,
    getDayDate,
    getWeek,
    numToText,
    EncryptEcb,
    DecryptEcb,
    delfileUploadDate,
    carDataProvince,
    carDataA_Z
}